package cn.my.learning.util;

import cn.my.learning.domain.User;
import cn.my.learning.repository.UserRepository;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;

import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * Created by Leo on 2017/4/6.
 * 邮件发送工具类
 */
public class EmailUtil {

    @Autowired
    private UserRepository userRepository;

    private SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

    private static final Logger logger = LoggerFactory.getLogger(EmailUtil.class);
    // 发件人的 邮箱 和 密码（替换为自己的邮箱和密码）
    // PS: 某些邮箱服务器为了增加邮箱本身密码的安全性，给 SMTP 客户端设置了独立密码（有的邮箱称为“授权码”）,对于开启了独立密码的邮箱, 这里的邮箱密码必需使用这个独立密码（授权码）。
    private static String myEmailAccount = "18666270636@163.com";
    private static String myEmailPassword = "379978424Leo";

    // 发件人邮箱的 SMTP 服务器地址, 必须准确, 不同邮件服务器地址不同, 一般(只是一般, 绝非绝对)格式为: smtp.xxx.com
    // 网易163邮箱的 SMTP 服务器地址为: smtp.163.com
    private static String myEmailSMTPHost = "smtp.163.com";

    //判断发送邮件的方式
    public String coreEmailController(String emailType, String emailContent, String emailTitle, String userEmailAddress, String username){
        /**
         * 第一：找回密码
         * 第二：发送邮件给全部人
         * 第三：发送邮件给某个用户
         */
        if (Objects.equals(emailType, "找回密码")){
            String randomString = getRandomString();
            String content = constructHTML(username, randomString,null, true);
            return sendEmailToUser(userEmailAddress, username, randomString, "码猿网密码重置邮件", content);
        }
        else if (Objects.equals(emailType, "全部人通知")){
            List<User> userList = userRepository.findAll();
            for (User user : userList){
                if (user.getEmail() != null || !Objects.equals(user.getEmail(), "")){
                    String content = constructHTML(user.getUsername(), null, emailContent, false);
                    sendEmailToUser(user.getEmail(), user.getUsername(), "AllPeople", emailTitle, content);
                }
            }
            return " System was sent email to all users already ! ";
        }
        else if(Objects.equals(emailType, "个人通知")){
            String content = constructHTML(username, null, emailContent, false);
            sendEmailToUser(userEmailAddress, username, "A User", emailTitle, content);
            return " System was sent email to target body ! ";
        }
        return null;
    }


    //发送邮件内容
    private String sendEmailToUser(String userEmailAddress, String username, String randomString, String emailTitle, String emailContent) {
        // 1. 创建参数配置, 用于连接邮件服务器的参数配置
        Properties props = new Properties();                    // 参数配置
        props.setProperty("mail.transport.protocol", "smtp");   // 使用的协议（JavaMail规范要求）
        props.setProperty("mail.smtp.host", myEmailSMTPHost);   // 发件人的邮箱的 SMTP 服务器地址
        props.setProperty("mail.smtp.auth", "true");            // 需要请求认证

        // 2. 根据配置创建会话对象, 用于和邮件服务器交互
        Session session = Session.getDefaultInstance(props);
        session.setDebug(true);                                 // 设置为debug模式, 可以查看详细的发送 log

        // 3. 创建一封邮件
        MimeMessage message = null;

        try {
            message = createMimeMessage(session, myEmailAccount, userEmailAddress, username, emailTitle, emailContent);

            // 4. 根据 Session 获取邮件传输对象
            Transport transport = session.getTransport();

            transport.connect(myEmailAccount, myEmailPassword);

            // 6. 发送邮件, 发到所有的收件地址, message.getAllRecipients() 获取到的是在创建邮件对象时添加的所有收件人, 抄送人, 密送人
            transport.sendMessage(message, message.getAllRecipients());

            // 7. 关闭连接
            transport.close();

            return randomString;

        } catch (Exception e) {
            e.printStackTrace();
        }

        return null;
    }

    /**
     * 创建一封只包含文本的简单邮件
     *
     * @param session 和服务器交互的会话
     * @param sendMailer 发件人邮箱
     * @param receiveMailer 收件人邮箱
     * @return
     * @throws Exception
     */
    private MimeMessage createMimeMessage(Session session, String sendMailer, String receiveMailer, String username, String emailTitle, String emailContent) throws Exception {
        // 1. 创建一封邮件
        MimeMessage message = new MimeMessage(session);

        // 2. From: 发件人
        message.setFrom(new InternetAddress(sendMailer, "码猿客服", "UTF-8"));

        // 3. To: 收件人（可以增加多个收件人、抄送、密送）
        message.setRecipient(MimeMessage.RecipientType.TO, new InternetAddress(receiveMailer, username + "用户", "UTF-8"));

        // 4. Subject: 邮件主题
        message.setSubject(emailTitle, "UTF-8");

        // 5. Content: 邮件正文（可以使用html标签）
        message.setContent(emailContent, "text/html;charset=UTF-8");

        // 6. 设置发件时间
        message.setSentDate(new Date());

        // 7. 保存设置
        message.saveChanges();

        return message;
    }

    //构造邮件模板
    private static String constructHTML(String username, String RandomString, String Content, boolean IsFindPassword){
        //邮件头部模板
        String head =
                "<td style=\"font-size: 16px; color:#555;line-height:26px; padding:20px 20px;\">" +
                "<p><strong>亲爱的" + username + "用户：</strong></p>";

        //邮件底部模板
        String footerContent =
                "</td>" +
                "</tr>" +
                "<tr>" +
                "<td style=\"font-size: 16px; color:#555;line-height:26px; padding:20px 20px;\">" +
                "码猿账号安全中心" +
                "<br>" +
                "<span style=\"border-bottom:1px dashed #ccc;\" t=\"5\" times=\" 12:13\">" +
                new SimpleDateFormat("yyyy-MM-dd").format(new Date()) +
                "</span> " +
                new SimpleDateFormat("HH:mm:ss").format(new Date()) +
                "</td>" +
                "</tr>";

        //区分在于IsFindPassword字段以及content
        if (IsFindPassword){
            //验证码邮件
            String verifyContent =
                    "<p>您好，您正在申请码猿博客的修改密码服务，本次请求的邮件验证码是：<strong>" + RandomString + "</strong>" +
                    "<br>" +
                    "（为了保障您账号的安全性，请您在5分钟内完成验证）<br>如非本人操作，请忽略该邮件，您的密码不会更改。" +
                    "<br>祝使用愉快！" +
                    "   </p>";

            return head + verifyContent + footerContent;
        }else {
            //普通邮件
            return head + Content + footerContent;
        }
    }

    /**
     * 验证码
     * @return
     */
    private static String getRandomString()
    {

        char[] chars={'1','2','3','4','5','6','7','8','9','0',
                'Q','W','E','R','T','Y','U','I','O', 'P','A','S','D','F','G','H','J','K','L','Z','X','C','V','B','N','M',
                'q','w','e','r','t','y','u','i','o', 'p','a','s','d','f','g','h','j','k','l','z','x','c','v','b','n','m'};
        Random random = new Random();
        StringBuilder stringBuffer =new StringBuilder();
        for(int i=0;i<=5;i++){
            stringBuffer.append(chars[random.nextInt(chars.length)]);
        }
        return stringBuffer.toString();
    }

    //获取生效时间
    public String getStartTime(){
        Date start_time = new Date();
        return dateFormat.format(start_time);
    }

    //获取失效时间
    public String getOutdateTime(String startTime) throws ParseException {
        Date end_time = new Date(dateFormat.parse(startTime).getTime() + 300000);
        return dateFormat.format(end_time);
    }

    //计算时间差
    public boolean detla_T(Date submitTime, String end_time, String start_time) throws ParseException {

        System.out.println(submitTime);

        //提交时间和结束时间以及生效时间进行对比
        int delta_T_toEnd = submitTime.compareTo(dateFormat.parse(end_time));
        int delta_T_toStart = submitTime.compareTo(dateFormat.parse(start_time));

        System.out.println(delta_T_toEnd);
        System.out.println(delta_T_toStart);

        if(delta_T_toStart>=0 && delta_T_toEnd<=0){
            logger.info("验证码提交时间 小于等于 验证码失效时间");
            logger.info("未失效");
            return true;
        }
        else {
            System.out.print("验证码提交时间 大于 验证码失效时间");
            logger.info("或验证码提交时间 小于 验证码发布时间");
            logger.info("失效");
            return false;
        }
    }
}
